package com.onlyforfun.exchange.view;

import android.app.AlertDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.onlyforfun.exchange.R;
import com.onlyforfun.exchange.domain.TimePrice;
import com.onlyforfun.exchange.util.CurrencyConverter;
import com.onlyforfun.exchange.util.NumberParse;
import com.onlyforfun.exchange.util.StringFormat;

public class ExchangeCalculateDialog extends DialogFragment {
	
	private TimePrice timepice;
	private double rate;
	private TextView china_currency = null;
	private TextView foreign_currency = null;
	public ExchangeCalculateDialog(TimePrice price, double rate) {
		this.timepice = price;
		this.rate = rate;
	}
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
    	AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
	    // Get the layout inflater
	    LayoutInflater inflater = getActivity().getLayoutInflater();
	
	    // Inflate and set the layout for the dialog
	    // Pass null as the parent view because its going in the dialog layout
	    View view = inflater.inflate(R.layout.exchange_calculate, null);
	    china_currency = (TextView) view.findViewById(R.id.china_currency);
	    china_currency.setText(StringFormat.valueOf(rate));
	    foreign_currency = (TextView) view.findViewById(R.id.foreign_currency);
	    foreign_currency.setText("100");
	    
	    foreign_currency.setOnFocusChangeListener(new OnFocusChangeListener() {
			
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus) {
					return;
				}
				TextView textView = (TextView) v;
				if ("".equals(textView.getText())) {
					return;
				}
				double input = NumberParse.parseMoneyDouble(textView.getText().toString());
				double currency = input / 100 * rate;
				china_currency.setText(StringFormat.valueOf(currency));
			}
		});
	    china_currency.setOnFocusChangeListener(new OnFocusChangeListener() {
			
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus) {
					return;
				}
				TextView textView = (TextView) v;
				if ("".equals(textView.getText())) {
					return;
				}
				double input = NumberParse.parseMoneyDouble(textView.getText().toString());
				if (rate == 0) {
					return;
				}
				double currency = 100 * input/ rate;
				foreign_currency.setText(StringFormat.valueOf(currency));
			}
		});
	    ImageView foreign_flag = (ImageView) view.findViewById(R.id.foreign_flag);
	    foreign_flag.setImageResource(CurrencyConverter.getIconByName(timepice.getName()));
	    builder.setView(view);  
	    return builder.create();
    }
}
